<?php
namespace Home\Controller;

class IndexController extends PublicController{
     public function index(){
        if(isset($_SESSION['my_info'])){
            $uid=$_SESSION["my_info"]["uid"];
            $userinfo=M("admin")->where(array("uid"=>$uid))->find();
            if($userinfo["roleid"]==1){//超级管理员
               $list=M("admin")->select();
               $flag=1;
            }else{
                $list[0]=$userinfo;
                $flag=0;
            }
            $this->assign("flag",$flag);
            $this->assign("list",$list);
          	$this->display();
        }
    }
    
    /**
     * roleid :1 超级管理员  2 子账号  3普通管理员
     */
    public function add(){
    	if($_POST){
    		$user = $_POST['username'];
    		$psd = $_POST['password'];
    		$psd1 = $_POST['password1'];
	    	$data['username'] = $_POST['username'];
	    	$data['password'] = md5($_POST['password']);
	        $data['time'] = time();
	        $data['times'] = date('Y-m-d H:i:s',time());
	        $data["roleid"]=I("post.roleid");
	        $data["roleid"]=intval($data["roleid"]);
	        if( $data["roleid"]==1){
	            $data["rolename"]="超级管理员";
	        }
	        elseif( $data["roleid"]==2){
	            $data["rolename"]="子账号";
	        }else{
	            $data["rolename"]="普通管理员";
	        }
	        if(empty($_POST['username'])){
	        	$this->error('用户名不能为空');
	        	exit;
	        }
	        if(empty($_POST['password'])){
	        	$this->error('密码不能为空');
	        	exit;
	        }

	        $select=M('admin')->where("username='$user'")->find();
	        if($select){
	        	$this->error('用户名存在');
	        	exit;
	        }
	        if($psd !== $psd1){
	           $this->error('两次密码不一致');
	           exit;
	        }
	        $add=M('admin')->add($data);
	        if($add){
	        	$this->success('添加成功',U('index/index'));
	        }else{
	        	$this->error('添加失败');
	        }
    	}else{
	    	$this->display();
    	}
    }
    
    public function update(){
    	   $id = $_GET['id'];
    	   $result=M('admin')->where("uid='$id'")->find();
    
    	   $this->assign('result',$result);
    	   if($_POST){
    	   	    $password = MD5($_POST['password']);
    	   	    $psd = MD5($_POST['password1']);
    	   	    if($password == $psd){
    	   	    	$update=M('admin')->where("uid='$id'")->setField('password',$password);
    	   	    	if($update || $result['password'] == $password){
    	   	    		$this->success('修改成功',U('index/index'));
    	   	    	}else{
    	   	    		$this->error('修改失败');
    	   	    	}
    	   	    }else{
    	   	    	$this->error('两次密码不一致');
    	   	    	exit;
    	   	    }
    	   }else{
    	    $this->display();
    	   }
    }
    
    public function del(){
    	  $id = $_GET['id'];
    	  $del=M('admin')->where("id='$id'")->delete();
    	  if($del){
    	  	   $this->success('删除成功',U('index/index'));
    	  }else{
    	  	   $this->error('删除失败');
    	  }
    }
}